package cn.zhibang.yygh2.service.cmn.service.impl;

import cn.zhibang.yygh2.common.util.util.BeanUtils;
import cn.zhibang.yygh2.model.model.cmn.Dict;
import cn.zhibang.yygh2.model.vo.cmn.DictEeVo;
import cn.zhibang.yygh2.service.cmn.listener.DictListener;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zhibang.yygh2.service.cmn.service.DictService;
import cn.zhibang.yygh2.service.cmn.mapper.DictMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
* @author Administrator
* @description 针对表【dict(组织架构表)】的数据库操作Service实现
* @createDate 2023-04-11 13:50:43
*/
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>
    implements DictService{

    /**
     * 根据上级id获取子节点数据列表
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChlidData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>(); //条件构造器
        wrapper.eq("parent_id", id);  //条件:parent_id=？
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            //通过查询判断每个节点下面是否还有子节点
            boolean isChild = this.isChildren(dictId);
            //修改hasChildren的值
            dict.setHasChildren(isChild);
        }
        return dictList;
    }

    /**
     * 导出
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //设置下载信息（导出就类似下载）
            response.setContentType("application/vnd.ms-excel");  //文件类型是excel
            response.setCharacterEncoding("utf-8"); //编码
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8"); //文件名及文件名编码
            // 也可以直接设置个名字：String fileName = "dict";
            response.setHeader("Content-disposition", "attachment;filename="+ fileName +".xlsx");
            //设置请求头，让操作以下载方式打开

            //查询数据库
            List<Dict> dictList = baseMapper.selectList(null);
            //将Dict对象转换成DictEeVo对象
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            for(Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                //转换
                BeanUtils.copyProperties(dict, dictEeVo);
                dictVoList.add(dictEeVo);
            }
            //写操作
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //导入数据字典
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
//读取
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //如果value能唯一定位数据字典，parentDictCode可以传空，例如：省市区的value值能够唯一确定
        if(StringUtils.isEmpty(parentDictCode)) {
            //注：这里使用baseMapper也可以，自动装配DictMapper也可以
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            if(null != dict) {
                return dict.getName();
            }
        } else {
            Dict parentDict = this.getByDictsCode(parentDictCode);
            if(null == parentDict) return "";
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", parentDict.getId()).eq("value", value));
            if(null != dict) {
                return dict.getName();
            }
        }
        return "";
    }


    /**
     * 根据dict_code查询Dict对象
     * @param parentDictCode
     * @return
     */
    private Dict getByDictsCode(String parentDictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", parentDictCode);
        return baseMapper.selectOne(wrapper);
    }


    /**
     * 判断id下面是否有子节点（并不查询出来）
     * @param id
     * @return
     */
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Long aLong = baseMapper.selectCount(wrapper);
        //count 0>0    1>0
        return aLong>0;
    }

    /**
     * 根据dicode查询下层节点
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取dict对象
        Dict codeDict = this.getByDictsCode(dictCode);
        if(null == codeDict) return null;
        //根据dict对象的id返回子节点集合
        return this.findChlidData(codeDict.getId());
    }



}




